<template>
  <div class="app-container">
    <el-card class="box-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Goods /></el-icon>
            <span class="header-title">商品详情管理</span>
          </div>
          <div class="header-right">
            <el-button v-if="route.params.productId" type="primary" :icon="Plus" :disabled="hasDetail" @click="handleAdd">新增详情</el-button>
            <el-button type="info" :icon="Back" @click="handleBack">返回</el-button>
          </div>
        </div>
      </template>

      <!-- 商品信息展示 -->
      <div v-if="productInfo" class="product-info">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="商品名称">{{ productInfo.name }}</el-descriptions-item>
          <el-descriptions-item label="商品编号">{{ productInfo.productNo }}</el-descriptions-item>
          <el-descriptions-item label="商品价格">¥{{ productInfo.price }}</el-descriptions-item>
          <el-descriptions-item label="品牌">{{ productInfo.brandName }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{ productInfo.categoryName }}</el-descriptions-item>
          <el-descriptions-item label="商品状态">
            <el-tag :type="productInfo.status === 1 ? 'success' : 'info'">
              {{ productInfo.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <el-table v-loading="loading" :data="detailList" border stripe highlight-current-row>
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="商品名称" align="center" prop="productInfo.name" width="80" /> -->
        <el-table-column label="副标题" align="center" prop="subtitle" min-width="150" show-overflow-tooltip />
        <el-table-column label="主图" align="center" min-width="100">
          <template #default="scope">
            <el-image
              v-if="scope.row.mainImage"
              :src="scope.row.mainImage"
              :preview-src-list="[scope.row.mainImage]"
              :preview-teleported="true"
              fit="cover"
              class="detail-image"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div v-else class="image-slot">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="容量" align="center" min-width="100">
          <template #default="scope"> {{ scope.row.volume }} {{ scope.row.unitName }} </template>
        </el-table-column>
        <el-table-column label="销量" align="center" prop="sales" width="100" />
        <el-table-column label="是否热销" align="center" prop="isHot" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isHot === 1 ? 'danger' : 'info'" effect="light">
              {{ scope.row.isHotName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="danger" link icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <!-- 添加或修改商品详情对话框 -->
    <el-dialog v-model="open" :title="title" width="700px" append-to-body destroy-on-close>
      <el-form ref="detailRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="商品编号" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入商品ID" disabled />
        </el-form-item>
        <el-form-item label="副标题" prop="subtitle">
          <el-input v-model="form.subtitle" placeholder="请输入副标题" />
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入商品描述" :rows="4" />
        </el-form-item>
        <el-form-item label="主图" prop="mainImage">
          <image-upload v-model="form.mainImage" :is-show-tip="false" :limit="1" />
        </el-form-item>
        <el-form-item label="子图" prop="subImages">
          <image-upload v-model="form.subImages" :is-show-tip="false" :limit="5" />
        </el-form-item>
        <el-form-item label="容量" prop="volume">
          <el-input-number v-model="form.volume" :min="0" :precision="2" :step="0.1" controls-position="right" style="width: 180px" />
        </el-form-item>
        <el-form-item label="单位" prop="unitId">
          <el-select
            v-model="form.unitId"
            placeholder="请选择单位"
            style="width: 180px"
            filterable
            remote
            :remote-method="handleUnitSearch"
            :loading="unitLoading"
            clearable
          >
            <el-option v-for="dict in unitOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="销量" prop="sales">
          <el-input-number v-model="form.sales" :min="0" controls-position="right" style="width: 180px" />
        </el-form-item>
        <el-form-item label="是否热销" prop="isHot">
          <el-radio-group v-model="form.isHot">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Edit, Delete, Goods, Picture, Back } from '@element-plus/icons-vue';
import { listProductDetail, getProductDetail, addProductDetail, updateProductDetail, delProductDetail } from '@/api/product/detail';
import { getProduct } from '@/api/product/product';
import { getProductUnitList } from '@/api/product/unit';
import type { ProductDetailVO } from '@/api/product/detail/types';
import type { ProductVO } from '@/api/product/product/types';
import type { ProductUnitVo, ProductUnitQuery } from '@/api/product/unit/types';
import ImageUpload from '@/components/ImageUpload/index.vue';

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const showSearch = ref(true);
const total = ref(0);
const detailList = ref<ProductDetailVO[]>([]);
const open = ref(false);
const title = ref('');
const hasDetail = ref(false);
const productInfo = ref<ProductVO>();
const detailRef = ref();

// 是否热销选项
const isHotOptions = [
  { value: 1, label: '是' },
  { value: 0, label: '否' }
];

// 单位选项
const unitOptions = ref<{ value: number; label: string }[]>([]);
const unitLoading = ref(false);
const unitKeyword = ref('');

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  productId: undefined,
  subtitle: undefined,
  isHot: undefined
});

// 表单参数
const form = ref<Partial<ProductDetailVO>>({
  productId: undefined,
  subtitle: '',
  description: '',
  mainImage: '',
  subImages: '',
  volume: 0,
  unitId: undefined,
  sales: 0,
  isHot: 0
});

// 表单校验
const rules = {
  productId: [{ required: true, message: '商品ID不能为空', trigger: 'blur' }],
  subtitle: [
    { required: true, message: '副标题不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '副标题长度必须在2到50个字符之间', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '商品描述不能为空', trigger: 'blur' },
    { min: 10, max: 500, message: '商品描述长度必须在10到500个字符之间', trigger: 'blur' }
  ],
  mainImage: [{ required: true, message: '主图不能为空', trigger: 'change' }],
  volume: [
    { required: true, message: '容量不能为空', trigger: 'blur' },
    { type: 'number', min: 0, message: '容量必须大于0', trigger: 'blur' }
  ],
  unitId: [{ required: true, message: '单位不能为空', trigger: 'change' }],
  sales: [
    { required: true, message: '销量不能为空', trigger: 'blur' },
    { type: 'number', min: 0, message: '销量必须大于等于0', trigger: 'blur' }
  ],
  isHot: [{ required: true, message: '请选择是否热销', trigger: 'change' }]
};

/** 获取单位列表 */
const getUnitOptions = async (keyword?: string) => {
  try {
    unitLoading.value = true;
    const params: ProductUnitQuery = {
      pageNum: 1,
      pageSize: 100,
      status: 1
    };
    if (keyword) {
      params.name = keyword;
    }
    const res = await getProductUnitList(params);
    unitOptions.value = res.rows.map((unit) => ({
      value: unit.id,
      label: `${unit.name}(${unit.symbol})`
    }));
  } catch (error) {
    console.error('获取单位列表失败:', error);
  } finally {
    unitLoading.value = false;
  }
};

/** 单位搜索处理 */
const handleUnitSearch = (query: string) => {
  if (query !== undefined) {
    unitKeyword.value = query.trim();
    getUnitOptions(unitKeyword.value);
  }
};

/** 查询商品详情列表 */
const getList = async () => {
  try {
    loading.value = true;
    // 如果是从商品管理页面跳转过来的，获取该商品的所有详情
    if (route.params.productId) {
      const response = await listProductDetail({
        productId: Number(route.params.productId)
      });
      console.log(response);
      if (response.rows) {
        detailList.value = response.rows;
        total.value = response.total;
        hasDetail.value = response.total > 0;
      } else {
        detailList.value = [];
        total.value = 0;
        hasDetail.value = false;
      }
    } else {
      // 否则获取列表
      const response = await listProductDetail(queryParams.value);
      detailList.value = response.data;
      total.value = response.total;
    }
  } catch (error) {
    console.error('获取商品详情失败:', error);
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    productId: undefined,
    subtitle: undefined,
    isHot: undefined
  };
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = () => {
  form.value = {
    productId: Number(route.params.productId),
    subtitle: '',
    description: '',
    mainImage: '',
    subImages: [],
    volume: 0,
    unitId: undefined,
    sales: 0,
    isHot: 0
  };
  open.value = true;
  title.value = '添加商品详情';
};

/** 修改按钮操作 */
const handleUpdate = async (row: ProductDetailVO) => {
  try {
    const response = await getProductDetail(row.id);
    const data = response.data;
    // 处理图片URL格式
    if (data.subImages && typeof data.subImages === 'string') {
      data.subImages = data.subImages.split(',').filter((url) => url.trim());
    }
    // 确保volume是数字类型
    if (data.volume) {
      data.volume = Number(data.volume);
    }
    form.value = data;
    open.value = true;
    title.value = '修改商品详情';
  } catch (error) {
    console.error('获取商品详情信息失败:', error);
  }
};

/** 提交按钮 */
const submitForm = async () => {
  try {
    // 表单验证
    await detailRef.value.validate();

    // 验证主图
    if (!form.value.mainImage) {
      ElMessage.error('请上传主图');
      return;
    }

    // 验证容量
    if (!form.value.volume || form.value.volume <= 0) {
      ElMessage.error('请输入有效的容量值');
      return;
    }

    // 验证单位
    if (!form.value.unitId) {
      ElMessage.error('请选择单位');
      return;
    }

    // 验证销量
    if (form.value.sales < 0) {
      ElMessage.error('销量不能为负数');
      return;
    }

    const submitData = { ...form.value };
    // 处理图片URL格式
    if (submitData.subImages) {
      if (Array.isArray(submitData.subImages)) {
        submitData.subImages = submitData.subImages.join(',');
      }
    }
    // 确保volume是数字类型
    if (submitData.volume) {
      submitData.volume = Number(submitData.volume);
    }

    if (submitData.id) {
      await updateProductDetail(submitData as ProductDetailVO);
      ElMessage.success('修改成功');
    } else {
      await addProductDetail(submitData as ProductDetailVO);
      ElMessage.success('新增成功');
    }
    open.value = false;
    getList();
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('表单验证失败，请检查必填项');
  }
};

/** 删除按钮操作 */
const handleDelete = async (row: ProductDetailVO) => {
  try {
    await ElMessageBox.confirm('是否确认删除该商品详情？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await delProductDetail([row.id]);
    ElMessage.success('删除成功');
    hasDetail.value = false;
    getList();
  } catch (error) {
    console.error('删除失败:', error);
  }
};

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  form.value = {
    productId: Number(route.params.productId),
    subtitle: '',
    description: '',
    mainImage: '',
    subImages: [],
    volume: 0,
    unitId: undefined,
    sales: 0,
    isHot: 0
  };
};

/** 获取商品信息 */
const getProductInfo = async (productId: number) => {
  try {
    const response = await getProduct(productId);
    productInfo.value = response.data;
  } catch (error) {
    console.error('获取商品信息失败:', error);
  }
};

/** 返回按钮操作 */
const handleBack = () => {
  router.push('/product/product');
};

onMounted(() => {
  // 从路由参数中获取商品ID
  if (route.params.productId) {
    const productId = Number(route.params.productId);
    queryParams.value.productId = productId;
    getProductInfo(productId);
  }
  getList();
  handleUnitSearch(''); // 页面加载时获取所有单位
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  min-height: calc(100vh - 120px);
  background-color: var(--el-bg-color-page);
}

.box-card {
  border-radius: 8px;
  height: 100%;
  transition: all 0.3s;
}

.box-card:hover {
  box-shadow: var(--el-box-shadow-light);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  padding: 0 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 28px;
  color: var(--el-color-primary);
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-form {
  margin-bottom: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.detail-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
  border: 1px solid var(--el-border-color-light);
  transition: all 0.3s;
  cursor: pointer;

  &:hover {
    transform: scale(1.05);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}

.image-slot {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--el-text-color-secondary);
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
  border: 1px solid var(--el-border-color-light);

  .el-icon {
    font-size: 24px;
  }
}

.image-slot .el-icon {
  font-size: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}

:deep(.el-input-number) {
  width: 180px;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px 32px;
  border-bottom: 1px solid var(--el-border-color-light);
}

:deep(.el-dialog__footer) {
  padding: 16px 32px;
  border-top: 1px solid var(--el-border-color-light);
}

.product-info {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
